package com.huadao.pda.login;

import android.content.Context;

import com.huadao.pda.common.ParamsConst;
import com.huadao.pda.common.UtilHelpers;
import com.huadao.pda.data.bean.DeviceInfo;
import com.huadao.pda.data.bean.User;
import com.huadao.pda.data.http.BaseImpl;
import com.huadao.pda.data.http.RockBaseObserver;
import com.huadao.pda.main.PdaApplication;
import com.huadao.pda.modle.DeviceInfoModle;
import com.huadao.pda.modle.LoginModle;
import com.huadao.pda.modle.ProjectModel;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

public class LoginPresenter extends ILoginContract.ILoginPresenter {

    private LoginModle loginModle;
    private DeviceInfoModle deviceInfoModle;
    private ProjectModel projectModel;
    private boolean isDeviceCreated;
//    private DeviceInfo deviceInfo;

    public LoginPresenter(ILoginContract.ILoginView baseView) {
        attachView(baseView);
        loginModle = new LoginModle(baseView.getContext());
        deviceInfoModle=new DeviceInfoModle(baseView.getContext());
        projectModel=new ProjectModel(baseView.getContext());
    }

    //登录前先创建设备
    @Override
    public void createDevice(String loadingMsg) {
        Observable<DeviceInfo> observable = deviceInfoModle.createAsync(UtilHelpers.getMacDefault(baseView.getContext()), 1);
        //理论上loading信息应该为"正在创建设备"
        deviceInfoModle.toSubscribe(observable, new RockBaseObserver<DeviceInfo>(this, loadingMsg) {
            @Override
            protected void onBaseNext(DeviceInfo deviceInfo) {
                isDeviceCreated=true;
                baseView.createDeviceResult(deviceInfo);
//                LoginPresenter.this.deviceInfo=deviceInfo;
            }
        });
    }

    @Override
    public void login(String userName, String password) {
        Observable<String> observable = loginModle.login(userName+ParamsConst.usernameSuffix, password);
        loginModle.toSubscribe(observable, new RockBaseObserver<String>(this, "正在登陆") {
            @Override
            protected void onBaseNext(String data) {
                baseView.onLoginResult(data);
                //登陆过后
                loginModle = new LoginModle(baseView.getContext());
            }
        });
    }

    @Override
    public boolean isDeviceCreated() {
        return isDeviceCreated;
    }

    @Override
    public void bindPDA() {
        Observable observable = projectModel.bindingPDA(PdaApplication.getInstance().getDevKeyId());
        deviceInfoModle.toSubscribe(observable, new RockBaseObserver(this, null) {
            @Override
            protected void onBaseNext(Object data) {

            }
        });
    }
}
